<template>
  <nav
      class="aui-navbar"
      :class="`aui-navbar--${$store.state.navbarLayoutType}`"
  >
    <div class="aui-navbar__header" style="width: 333px;">
      <h1 class="aui-navbar__brand" @click="$router.push({ name: 'home' })">
        <a class="aui-navbar__brand-lg" href="javascript:;" style="display: flex;align-items: center;">
          <img data-v-fb5915c2=""
                 :src="$ossLink+'/app/gif/'+$store.state.siteWebConfig.icon"
                 height="28"
                 v-if="$store.state.siteWebConfig.icon"
                 alt="MSPBOTS Portal"
                 style="cursor: pointer;">
            <span style="font-size: 20px;font-weight: bold;margin-left: 12px;">{{$store.state.siteWebConfig.title}}</span>
        </a>
      </h1>
    </div>
    <div class="aui-navbar__body menu-right-all">
      <el-menu class="aui-navbar__menu mr-auto" mode="horizontal">
        <el-tooltip
            :open-delay="1000"
            class="item"
            effect="dark"
            :content="$t('main.refresh')"
            placement="right"
        >
          <el-menu-item
              index="2"
              id="refresh"
              @click="
                refresh()
                refreshRequestBundle()
              "
          >
            <i class="cuifont icon_arrow_sync" style="font-weight: bold"></i>
          </el-menu-item>
        </el-tooltip>
        <el-menu-item index="3"
                          @click="gotopage()" v-if="$hasPermission('sys:control:truck')">
              <i class="el-icon-truck"
                 style="font-weight: bold;"></i>
        </el-menu-item>
        <el-menu-item index="77">
          <request-bundle
              v-if="
                showRequestBundleBtn &&
                $store.state.user.tenantName !== 'mspbots.ai'
              "
          ></request-bundle>
        </el-menu-item>
      </el-menu>

        <el-menu class="aui-navbar__menu" mode="horizontal">
           <!-- v-if="$hasPermission('sys:superadminauth')" -->
          <el-menu-item index="888"
                        v-if="$hasPermission('sys:system:upgrade-sql')">
            <el-checkbox @change="groupMergeFlag"
                         :value="$store.state.system.groupMergeFlag"></el-checkbox>
          </el-menu-item>
          <!-- <el-menu-item index="7"
                        @click="showShare = true">Refer and Earn</el-menu-item> -->
          <el-menu-item>
            <!-- <notice></notice> -->
          </el-menu-item>
          <el-menu-item index="1"
                        v-if="isSwitchTenantAuth"
                        class="tenant-info-item">
            <el-button v-if="isSwitchTenantAuth"
                       size="small"
                       type="text"
                       @click.native="tenantHandle()">
              <i class="el-icon-house el-icon--right"></i>{{ $t('tenant.current') }}: {{ $store.state.user.tenantName }}
            </el-button>
            <span v-else
              ><i class="el-icon-house el-icon--right"></i
              >{{ $t('tenant.current') }}:
              {{ $store.state.user.tenantName }}</span
          >
        </el-menu-item>
        <!-- <el-menu-item>
          <Forum />
        </el-menu-item> -->
        <el-menu-item index="2" v-if="isShowGetStartedBtn">
          <el-button size="mini" @click="openGetStarted" type="primary">{{
              $t('custom.topMenu.getStarted')
            }}</el-button>
        </el-menu-item>
        <el-menu-item index="5" @click="fullscreenHandle()">
          <svg class="icon-svg aui-navbar__icon-menu" aria-hidden="true">
            <use xlink:href="#icon-fullscreen"></use>
          </svg>
        </el-menu-item>
        <!-- <el-menu-item index="6">{{ $store.state.user.username }}</el-menu-item> -->
        <el-menu-item index="6" class="aui-navbar__avatar">
          <!-- <el-tooltip :open-delay="1000" effect="dark" placement="bottom">
            <div slot="content">{{this.$store.state.user.tenantName}}
              <br v-if='this.$store.state.user.username'/>{{this.$store.state.user.username}}
              <br v-if='"" !== getRole(this.$store.state.user.roleList)' />
                <div style="max-width:150px;">
                  {{getRole(this.$store.state.user.roleList)}}
                </div>
              </div>
          <span>{{ realName }}&nbsp;</span>
          </el-tooltip>  -->
          <el-dropdown placement="bottom" :show-timeout="0" trigger="click" @visible-change="hideSearch">
              <span class="el-dropdown-link">
                <el-image :src="headUrl" fit="cover">
                  <img
                      slot="error"
                      fit="cover"
                      src="~@/assets/mspbots/default_avatar.png"
                      style="max-width: 30px; max-height: 30px"
                  />
                </el-image>
                <!-- <i class="el-icon-arrow-down"></i> -->
              </span>
            <el-dropdown-menu slot="dropdown" style="width: 280px">
              <div
                  style="
                    display: flex;
                    height: 80px;
                    border-bottom: 0.5px solid #c0c0c0;
                  "
              >
                <div style="margin-left: 16px; align-self: center">
                  <img
                      :src="headUrl"
                      fit="cover"
                      style="
                        width: 50px !important;
                        height: 50px !important;
                        max-width: 50px !important;
                        max-height: 50px !important;
                        border-radius: 100%;
                      "
                  />
                  <!-- <img slot="error"
                         fit="cover"
                         src="~@/assets/mspbots/default_avatar.png"
                          /> -->
                </div>
                <div style="margin-top: 16px; margin-left: 16px">
                  <div style="display: flex; flex-direction: column">
                    <span>{{ realName }}</span>
                    <span style="color: #8492a6; font-size: 13px">{{
                        this.$store.state.user.username
                      }}</span>
                    <el-tooltip
                        :open-delay="1000"
                        effect="dark"
                        placement="bottom"
                    >
                      <div slot="content">
                        {{ getRole(this.$store.state.user.roleList) }}
                      </div>
                      <div
                          style="
                            max-width: 175px;
                            color: #8492a6;
                            font-size: 13px;
                            word-break: break-word;
                            overflow: hidden;
                            text-overflow: ellipsis;
                            display: -webkit-box;
                            -webkit-line-clamp: 2;
                            -webkit-box-orient: vertical;
                          "
                      >
                        {{ getRole(this.$store.state.user.roleList) }}
                      </div>
                    </el-tooltip>
                  </div>
                </div>
              </div>
              <!-- <el-divider style="margin:6px;"></el-divider> -->
              <div class="search-box">
                <template v-if="!searchAccount">
                  <span class="switch-to" >{{$t('switchaccount') }}</span>
                  <span @click="searchAccount = true" class="icon cuifont icon_search"></span>
                </template>
                <el-input v-show="searchAccount" size="mini" placeholder="search" id="searchAccount" prefix-icon="el-icon-search" v-model="search"></el-input>
              </div>
              <!-- <el-dropdown-item  v-if="this.$store.state.user.regSource === '3'" @click.native="updatePasswordHandle()">{{ $t('updatePassword.title') }}</el-dropdown-item> -->
              <div class="search-noData" v-if="(switchAccountList.filter(data => !search || data.tenantName.toLowerCase().includes(search.toLowerCase()))).length === 0">No results</div>
              <div class="tenant-list">
              <el-dropdown-item
                  v-for="(item, index) in switchAccountList.filter(data => !search || data.tenantName.toLowerCase().includes(search.toLowerCase()))"
                  :key="index"
                  @click.native="switchAccount(item)"
                  style="cursor: pointer; padding: 0 0;"
              >
                <div style="display: flex; flex-direction: column;">
                  <div
                      v-if="isMe(item)"
                      style="display: flex; align-items: center; justify-content: left;position: relative"
                  >
                    <div
                        style="
                          position: absolute;
                          left: 4px;
                          top: 50%;
                          transform: translateY(-50%);
                          width: 4px;
                          height: 24px;
                          border-radius: 1px;
                          background-color: #45c2b5;
                        "
                    ></div>
                    <el-button
                        class="cuifont icon_briefcase"
                        style="
                          font-size: 14px;
                          cursor: pointer;
                          padding: 8px;
                          margin-left: 20px;
                        "
                    ></el-button>
                    <span
                        v-if="isMe(item)"
                        :style="{ fontWeight: isMe(item) ? 'bold' : '' }"
                        style="margin-left: 8px"
                    >{{ item.tenantName }}</span
                    >
                  </div>
                  <div v-else>
                    <el-button
                        class="cuifont icon_briefcase"
                        style="
                          font-size: 14px;
                          cursor: pointer;
                          padding: 8px;
                          margin-left: 20px;
                        "
                    ></el-button>
                    <span style="margin-left: 8px">{{
                        item.tenantName
                      }}</span>
                  </div>
                </div>
                </el-dropdown-item>
              </div>
                <system-theme></system-theme>
                <el-dropdown-item
                  @click.native="logoutHandle()"
                  style="color: #e02020"
                  divided
              >{{ $t('logout') }}</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </el-menu-item>
      </el-menu>
    </div>
    <update-password
        v-if="updatePasswordVisible"
        ref="updatePassowrd"
    ></update-password>
    <switch-tenant
        v-if="switchTenantVisible"
        ref="switchTenant"
    ></switch-tenant>
    <share-third-party :visible.sync="showShare"></share-third-party>
  </nav>
</template>

<script>
import { messages } from '@/i18n'
import screenfull from 'screenfull'
import UpdatePassword from './main-navbar-update-password'
import SwitchTenant from './main-navbar-switch-tenant'
import { getUUID, clearLoginInfo, loginSourcePathURL } from '@/utils'
import { removeToken } from '@/components/storybook/utilties/auth'
import SubMenu from './main-sidebar-sub-menu'
import Forum from './main-navbar-forum'
import init from '@/utils/websocket'
import shareThirdParty from '@/components/share-third-party'
import notice from '@/views/navBarComponent/navbar-notice/notice.vue'
import requestBundle from '@/components/request-bundle'
import { timeFormat } from '@/components/storybook/utilties/tools'
import useErrorMessage from '@/components/storybook/hooks/useErrorMessage'
import Cookies from 'js-cookie'
import { useMsal, msalInstance } from '@/components/storybook/hooks/useMsal'

const { logoutPopup } = useMsal()
import systemTheme from './theme/theme.vue'

export default {
  inject: {
    refresh:{
      default:()=>function(){}
    }
  },
  data() {
    return {
      i18nMessages: messages,
      updatePasswordVisible: false,
      messageTip: false,
      switchTenantVisible: false,
      showShare: false,
      showRequestBundleBtn: true,
      notifyInstance: null,
      timer: null,
      hidden: null,
      visibilityChange: null,
      search: '',
      searchAccount: false,
    }
  },
  computed: {
    theme () {
      return this.$store.state.app.theme
    },
    pageHiddenTime () {
      if (window.location.hostname === 'localhost' ) {
        return false
      }
      if(!window.SITE_CONFIG['dictList'].find(e => e.dictType === 'page_hidden_time')){
        return false
      }
      return Number(window.SITE_CONFIG['dictList'].find(e => e.dictType === 'page_hidden_time').dataList[0].dictValue)
    },
    headUrl() {
      return this.$store.state.user.headUrl
        ? this.$store.state.user.headUrl
        : this.$ossLink + '/app/other/default_avatar.png'
    },
    realName() {
      if (this.$store.state.user.realName) {
        return this.$store.state.user.realName
      } else {
      }
    },
    isShowGetStartedBtn() {
      let hasUndoneStatus = true
      if (
        this.$store.state.GetStarted.configList.findIndex(
          e => e.status === 'undone'
        ) === -1
      ) {
        hasUndoneStatus = false
      } else {
        hasUndoneStatus = true
      }
      return hasUndoneStatus
    },
    isSwitchTenantAuth() {
      let adminAuth = this.$hasPermission('sys:superadminauth') ? 1 : 0
      let roleId = sessionStorage.getItem('loginAsRoleId') ? 1 : 0
      let userId = sessionStorage.getItem('loginAsUserId') ? 1 : 0
      if (adminAuth + roleId + userId >= 1) {
        return true
      } else {
        return false
      }
    },
    switchAccountList() {
      let temp = []
      let tempList = []
      temp = this.$store.state.user.tenantList
      for (let i = 0; i < temp.length; i++) {
        const element = temp[i]
        if (element.regSource === '1' || element.regSource === '5') {
          tempList.push(element)
        }
      }
      return this._.uniq(tempList)
    }
  },
  components: {
    shareThirdParty,
    requestBundle,
    UpdatePassword,
    SwitchTenant,
    SubMenu,
    notice,
    Forum,
    systemTheme
  },
  mounted () {
    // this.openTimer()
    // document.addEventListener("keydown", event => {
    //   if (event.code === 'Backspace' && !this.search) {
    //     this.searchAccount= false
    //   }
    //   this.openTimer()
    // });
    // document.addEventListener("mousemove", () => {
    //   this.openTimer()
    // });
    this.$router.replace({ name: 'desktop' })
  },
  created() {
    if (typeof document.hidden !== "undefined") {
      this.hidden = "hidden";
      this.visibilityChange = "visibilitychange";
    } else if (typeof document.mozHidden !== "undefined") {
      this.hidden = "mozHidden";
      this.visibilityChange = "mozvisibilitychange";
    } else if (typeof document.msHidden !== "undefined") {
      this.hidden = "msHidden";
      this.visibilityChange = "msvisibilitychange";
    } else if (typeof document.webkitHidden !== "undefined") {
      this.hidden = "webkitHidden";
      this.visibilityChange = "webkitvisibilitychange";
    }
    document.addEventListener(this.visibilityChange, this.openTimer);
    this.$store.state.sidebarMenuList = window.SITE_CONFIG['menuList']
    if (Cookies.get('token')) init(this.loda)
  },
  beforeDestroy() {
    document.removeEventListener(this.visibilityChange, this.openTimer)
    this.$store.state.app.WebSocket.onclose = e => {
      init(this.loda())
      this.$store.state.app.WebSocket = null
    }
  },
  methods: {
    openTimer(){
      if (this.timer) clearTimeout(this.timer)
      if (document[this.hidden]) {
        if(this.pageHiddenTime){
          this.timer = setTimeout(() => {
          this.logoutHandle(true)
        }, this.pageHiddenTime*60*1000);
        }
      }
    },
    groupMergeFlag() {
      this.$store.commit('SET_UPGRADE_SQL')
    },
    refreshRequestBundle() {
      this.showRequestBundleBtn = false
      this.$nextTick(() => {
        this.showRequestBundleBtn = true
      })
    },
    loda(data) {
      this.notifyInstance && this.notifyInstance.close()
      if (data.businessType === 'deploy') {
        if (data.data.alert && data.data.action && data.data.action === 'DEPLOY_FINISHED') {
          const time = timeFormat(data.data.createTime, 'HH:mm')
          this.notifyInstance = this.$notify({
            title: data.data.title,
            customClass: 'notify-custom',
            message: `<div>
              <div>${data.data.msg}</div>
              <div>${time}</div>
            </div>`,
            type: data.data.type,
            dangerouslyUseHTMLString: true,
            offset: 45,
            duration: 0
          })
          return
        }
      }

      this.$store.dispatch('setDayLeft')
      if (!data) return
      if (data.businessType === 'bot') {
        this.notifyInstance = this.$notify({
          title: data.data.title,
          message: data.data.content,
          type: data.data.type,
          dangerouslyUseHTMLString: true,
          offset: 45,
          duration: 0
        })
      }
    },
    myNoticeRouter() {
      this.$router.replace('notice-notice-user')
    },
    getUnReadCount() {
      this.$interface.system
        .getUnreadMessageApi()
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          if (res.data > 0) {
            this.messageTip = true
          }
        })
        .catch(() => {})
    },
    fullscreenHandle() {
      if (!screenfull.enabled) {
        return this.$message({
          message: this.$t('fullscreen.prompt'),
          type: 'warning',
          duration: 500
        })
      }
      if (!screenfull.isFullscreen) {
        this.$store.state.sidebarFold = true
      } else {
        this.$store.state.sidebarFold =
          localStorage.getItem('sidebarFold') != null
            ? localStorage.getItem('sidebarFold')
            : true
      }
      screenfull.toggle()
    },
    tenantHandle() {
      this.switchTenantVisible = true
      this.$nextTick(() => {
        this.$refs.switchTenant.init()
      })
    },
    updatePasswordHandle() {
      this.updatePasswordVisible = true
      this.$nextTick(() => {
        this.$refs.updatePassowrd.init()
      })
    },

    async logoutHandle(noTips=false) {
      try {
        if(!noTips){
          await this.$confirm(
            this.$t('prompt.info', { handle: this.$t('logout') }),
            this.$t('prompt.title'),
            {
              confirmButtonText: this.$t('confirm'),
              cancelButtonText: this.$t('cancel'),
              type: 'warning'
            }
          )
        }
        const { userLogoutApi } = this.$interface.system
        const { data: response } = await userLogoutApi()
        if (response.code !== 0) {
          throw response.msg
        }
        this.$store.state.contentTabs = []
        let temp = loginSourcePathURL()
        if (this.$store.state.user.microsoftId) {
          const request=noTips?{account: msalInstance.getAccountByHomeId(localStorage.getItem('homeAccountId')),onRedirectNavigate: ()=>clearLoginInfo()}:{onRedirectNavigate: ()=>clearLoginInfo()}
          await logoutPopup(request)
          sessionStorage.setItem('redirectLoginUrl', `/${temp}`)
        } else {
          clearLoginInfo()
          this.$router.push(`/${temp}`, () => {
            this.$store.state.permission.routes = []
            sessionStorage.setItem(
              'redirectLoginUrl',
              `/${temp}`
            )
          })
        }
      } catch (error) {
        useErrorMessage(error)
      }
    },
    openGetStarted() {
      this.$store.state.GetStarted.dialogStatus = true
      try {
        const hasUndoneSteps =
          this.$store.state.GetStarted.configList.findIndex(
            e => e.status === 'undone'
          )
        if (hasUndoneSteps !== -1) {
          this.$store.state.GetStarted.steps = hasUndoneSteps
        } else {
          this.$store.state.GetStarted.steps = 0
        }
      } catch (error) {}
      setTimeout(() => {
        this.$store.state.GetStarted.dialogStatus = false
      }, 100)
    },
    getRole(roleList) {
      let arr = []
      if (roleList) {
        roleList.forEach(item => {
          arr.push(item.name)
        })
      }
      return arr.join(',')
    },
    isMe(data) {
      let temp = false
      if (data.tenantCode === this.$store.state.user.tenantCode) {
        temp = true
      }
      return temp
    },
    switchAccount(data) {
      if (data.tenantCode === this.$store.state.user.tenantCode) {
        return
      }
      this.$emit('load')
      const params = {
        switchUser: true,
        username: data.username,
        uuid: getUUID(),
        password: data.username,
        tenantCode: data.tenantCode
      }
      this.$interface.login
        .webLoginApi(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.setCookies(res.data)
          this.removeSlicerLocalStorage()
          this.loginSuccess()
        })
        .catch(() => {})
    },
    removeSlicerLocalStorage(){
      let slicerArr = [
        '-dropdown-list-gadget-',
        '-date-slicer-gadget',
        '-customized-multi-select-gadget',
        '-userdropdown-list-gadget-',
        '-user-multi-select-gadget-',
        '-multi-select-gadget']
         for (let  key in localStorage) {
             slicerArr.forEach(item=>{
              if (key.includes(item)) {
                localStorage.removeItem(key)
              }
          })
        }
    },
    loginSuccess() {
      this.$interface.login
        .loginUserInfoApi()
        .then(res => {
          if (res.data.code !== 0) {
            this.$store.commit('SET_API_LOAD_STATUS', false)
            return this.$message.error(res.data.msg)
          }
          this.$store.commit('SET_API_LOAD_STATUS', false)
          this.$store.commit('SET_LOGIN_USER_INFO', res.data.data)
          this.$store.state.contentTabs =
            window.SITE_CONFIG['routerWithForgetToken']
          // window.location.reload()     
          this.$router.replace({ path: '/home' }).then(()=>{
             window.location.reload()
          }).catch(()=>{
             window.location.reload()
          })
        })
        .catch(() => {
          this.$store.commit('SET_API_LOAD_STATUS', false)
        })
    },
    setCookies(data) {
      window.location.protocol === 'https:'? Cookies.set('token', data.token, { sameSite: 'None', secure: true }) : Cookies.set('token', data.token)
      window.location.protocol === 'https:'? Cookies.set('tenant_code', data.tenantCode, {
        sameSite: 'None',
        secure: true
      }) : Cookies.set('tenant_code', data.tenantCode)
      sessionStorage.setItem('isMySelfCode', data.tenantCode)
      sessionStorage.setItem('isMySelfName', data.tenantName)
    },
    hideSearch (val) {
      if (!val) {
        this.search = ''
        this.searchAccount = false
      }
    },
    gotopage () {
      this.$router.replace({ name: 'desktop' })
    }
  }
}
</script>
<style lang="scss" scoped>
.menu-right-all {
  display: flex;
  justify-content: space-between;
}

.menu-block-css {
  width: calc(100% - 700px);
  overflow: auto;
  display: flex;
  &::-webkit-scrollbar {
    width: 10px;
    height: 0px;
  }
  &::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background-color: skyblue;
    background-image: -webkit-linear-gradient(
      45deg,
      rgba(255, 255, 255, 0.2) 25%,
      transparent 25%,
      transparent 50%,
      rgba(255, 255, 255, 0.2) 50%,
      rgba(255, 255, 255, 0.2) 75%,
      transparent 75%,
      transparent
    );
  }
  &::-webkit-scrollbar-track {
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #ededed;
    border-radius: 10px;
  }
}
.tenant-info-item {
  & > .el-button {
    width: 160px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.el-image {
  max-width: 30px;
  max-height: 30px;
  width: 36px;
  height: auto;
  margin-right: 5px;
  border-radius: 100%;
  vertical-align: middle;
}
.search-box {
  display: flex;
  padding: 0 20px;
  height: 42px;
  align-items: center;
  justify-content: space-between;
  .icon_search {
    cursor: pointer;
  }
  .switch-to {
    color: #0000009C;
    font-weight: bold;
  }
}
.search-noData {
  text-align: center;
  line-height: 34px;
  color: #00000073;
  font-weight: bold;
}
.tenant-list{
  max-height: 200px;
  overflow: auto;
}
.item-icon {
  display: inline-block;
  margin-left: 12px;
  width: 24px;
  height: 24px;
  text-align: center;
  line-height: 24px;
  border-radius: 4px;
  border: 1px solid #0000000F;
}
</style>

<style lang="scss">
.notify-custom {
  .el-notification__content {
    text-align: left !important;
  }
}
</style>
